package org.example.java.util.concurrency.catch_exception;

import com.sun.istack.internal.NotNull;

import java.util.concurrent.*;

/**
 * Created by Juntao.Zhang on 2014/10/25.
 */
public class HandlerThreadFactoryTest2 {
  static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
      System.err.println("caught " + e);
      e.printStackTrace();
    }
  }

  static class HandlerThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(@NotNull Runnable r) {
      System.out.println(this + " creating new Thread");
      Thread t = new Thread(r);
      System.out.println("created " + t + " ID:" + t.getId());
      t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
      System.out.println("eh=" + t.getUncaughtExceptionHandler());
      return t;
    }
  }

  static class MyRunner implements Runnable {
    int count = 0;
    boolean flag = true;

    @Override
    public void run() {
      while (flag) {
        count++;
        System.out.println("run finish");
        try {
          TimeUnit.SECONDS.sleep(1);
          if (count == 2) {
//              flag = false;
//            System.exit(-1);
            throw new RuntimeException("my simple get test");
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public static void main(String[] args) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new HandlerThreadFactory());
    ScheduledFuture future = executor.scheduleWithFixedDelay(new MyRunner(), 0, 1000, TimeUnit.MILLISECONDS);

    executor.shutdown();

//    executor.scheduleWithFixedDelay(new Runnable() {
//      @Override
//      public void run() {
//        int count=100;
//        while (count-->0){
//          System.out.print(".");
//        }
//        System.out.println();
//      }
//    }, 1, 1, TimeUnit.SECONDS);
//    try {
//      System.out.println("== finish ==");
//      System.out.println("get=>"+future.get());
//    } catch (Exception e) {
//      e.printStackTrace();
//    }

//    new Thread(new MyRunner()).start();
  }
}
